import { SearchOutlined } from '@ant-design/icons'
import { Button, Input, Space, Table } from 'antd'
import React, { useRef, useState, useEffect, memo } from 'react'
import Highlighter from 'react-highlight-words'

const PlugincardPower = ({ dataOfPlugincardPower }) => {
  const [searchText, setSearchText] = useState('')
  const [searchedColumn, setSearchedColumn] = useState('')
  const searchInput = useRef(null)
  const [dataSource, setDataSource] = useState(null)

  useEffect(() => {
    if (dataOfPlugincardPower) {
      dataOfPlugincardPower.map((item) => {
        item.invalidrate = Number(item.invalid / item.sumcount * 100).toFixed(2) + '%'
        return item
      })
      const dataSource = dataOfPlugincardPower.map((hotelRoom) => (
        {
          key: hotelRoom.registerId,
          hotelname: hotelRoom.hotelname,
          roomname: hotelRoom.roomname,
          sumcount: hotelRoom.sumcount,
          invalid: hotelRoom.invalid,
          invalidrate: hotelRoom.invalidrate,
        }
      ))
      setDataSource(dataSource)
    }
  }, [dataOfPlugincardPower])

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm()
    setSearchText(selectedKeys[0])
    setSearchedColumn(dataIndex)
  }

  const handleReset = (clearFilters) => {
    clearFilters()
    setSearchText('')
  }

  const getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div
        style={{
          padding: 8,
        }}
      >
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: 'block',
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            Search
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            Reset
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({
                closeDropdown: false,
              })
              setSearchText(selectedKeys[0])
              setSearchedColumn(dataIndex)
            }}
          >
            Filter
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? '#1890ff' : undefined,
        }}
      />
    ),
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100)
      }
    },
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{
            backgroundColor: '#ffc069',
            padding: 0,
          }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (
        text
      ),
  })

  const columns = [
    {
      title: '酒店名称',
      dataIndex: 'hotelname',
      key: 'hotelname',
      width: '20%',
      ...getColumnSearchProps('hotelname'),
    },
    {
      title: '房间号',
      dataIndex: 'roomname',
      key: 'roomname',
      width: '20%',
      ...getColumnSearchProps('roomname'),
    },
    {
      title: '读取次数',
      dataIndex: 'sumcount',
      key: 'sumcount',

      sorter: (a, b) => a.sumcount - b.sumcount,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '无效次数',
      dataIndex: 'invalid',
      key: 'invalid',

      sorter: (a, b) => a.invalid - b.invalid,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '无效占比',
      dataIndex: 'invalidrate',
      key: 'invalidrate',

      sorter: (a, b) => a.invalidrate.replace("%", "") - b.invalidrate.replace("%", ""),
      sortDirections: ['descend', 'ascend'],
    },
  ]

  return (
    <>
      <Table columns={columns} dataSource={dataSource} />
    </>
  )
}

export default memo(PlugincardPower)